package com.lktx.sso.admin.controller;

import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.server.util.JsonResult;
import cn.hserver.plugin.web.annotation.Controller;
import cn.hserver.plugin.web.annotation.GET;
import cn.hserver.plugin.web.annotation.POST;
import cn.hserver.plugin.web.interfaces.HttpRequest;
import cn.hserver.plugin.web.interfaces.HttpResponse;
import cn.hutool.core.util.StrUtil;
import com.lktx.sso.admin.entity.SsoFiles;
import com.lktx.sso.admin.service.SsoFilesService;
import com.lktx.sso.system.common.MyResult;

import java.io.File;

@Controller("/api/file/")
public class ResourceController {

    @Autowired
    private SsoFilesService filesService;

    @POST("upload")
    public MyResult uploadFiles(HttpRequest request) {
        String s = filesService.uploadFiles(request);
        if (s != null) {
            return MyResult.of(s);
        }
        return MyResult.failure();
    }

    @GET("{id}")
    public void getFile(String id, HttpResponse response) {
        if (StrUtil.isEmpty(id)) {
            response.sendJson(JsonResult.error("文件编码不存在"));
            return;
        }
        SsoFiles byId = filesService.getById(id);
        if (byId == null || !new File(byId.getFilePath()).exists()) {
            response.sendJson(JsonResult.error("文件不存在"));
            return;
        }
        response.setDownloadFile(new File(byId.getFilePath()));
    }

}